/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import dao.exceptions.IllegalOrphanException;
import dao.exceptions.NonexistentEntityException;
import dao.exceptions.RollbackFailureException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.UserTransaction;
import pojos.Customers;
import pojos.Projects;
import java.util.ArrayList;
import java.util.Collection;

/**
 *
 * @author A7med Kotb
 */
public class CustomersJpaController implements Serializable {

    public CustomersJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Customers customers) throws RollbackFailureException, Exception {
        if (customers.getProjectsCollection() == null) {
            customers.setProjectsCollection(new ArrayList<Projects>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Projects> attachedProjectsCollection = new ArrayList<Projects>();
            for (Projects projectsCollectionProjectsToAttach : customers.getProjectsCollection()) {
                projectsCollectionProjectsToAttach = em.getReference(projectsCollectionProjectsToAttach.getClass(), projectsCollectionProjectsToAttach.getProId());
                attachedProjectsCollection.add(projectsCollectionProjectsToAttach);
            }
            customers.setProjectsCollection(attachedProjectsCollection);
            em.persist(customers);
            for (Projects projectsCollectionProjects : customers.getProjectsCollection()) {
                Customers oldCustomerOfProjectsCollectionProjects = projectsCollectionProjects.getCustomer();
                projectsCollectionProjects.setCustomer(customers);
                projectsCollectionProjects = em.merge(projectsCollectionProjects);
                if (oldCustomerOfProjectsCollectionProjects != null) {
                    oldCustomerOfProjectsCollectionProjects.getProjectsCollection().remove(projectsCollectionProjects);
                    oldCustomerOfProjectsCollectionProjects = em.merge(oldCustomerOfProjectsCollectionProjects);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Customers customers) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Customers persistentCustomers = em.find(Customers.class, customers.getCustId());
            Collection<Projects> projectsCollectionOld = persistentCustomers.getProjectsCollection();
            Collection<Projects> projectsCollectionNew = customers.getProjectsCollection();
            List<String> illegalOrphanMessages = null;
            for (Projects projectsCollectionOldProjects : projectsCollectionOld) {
                if (!projectsCollectionNew.contains(projectsCollectionOldProjects)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Projects " + projectsCollectionOldProjects + " since its customer field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Projects> attachedProjectsCollectionNew = new ArrayList<Projects>();
            for (Projects projectsCollectionNewProjectsToAttach : projectsCollectionNew) {
                projectsCollectionNewProjectsToAttach = em.getReference(projectsCollectionNewProjectsToAttach.getClass(), projectsCollectionNewProjectsToAttach.getProId());
                attachedProjectsCollectionNew.add(projectsCollectionNewProjectsToAttach);
            }
            projectsCollectionNew = attachedProjectsCollectionNew;
            customers.setProjectsCollection(projectsCollectionNew);
            customers = em.merge(customers);
            for (Projects projectsCollectionNewProjects : projectsCollectionNew) {
                if (!projectsCollectionOld.contains(projectsCollectionNewProjects)) {
                    Customers oldCustomerOfProjectsCollectionNewProjects = projectsCollectionNewProjects.getCustomer();
                    projectsCollectionNewProjects.setCustomer(customers);
                    projectsCollectionNewProjects = em.merge(projectsCollectionNewProjects);
                    if (oldCustomerOfProjectsCollectionNewProjects != null && !oldCustomerOfProjectsCollectionNewProjects.equals(customers)) {
                        oldCustomerOfProjectsCollectionNewProjects.getProjectsCollection().remove(projectsCollectionNewProjects);
                        oldCustomerOfProjectsCollectionNewProjects = em.merge(oldCustomerOfProjectsCollectionNewProjects);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = customers.getCustId();
                if (findCustomers(id) == null) {
                    throw new NonexistentEntityException("The customers with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Customers customers;
            try {
                customers = em.getReference(Customers.class, id);
                customers.getCustId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The customers with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Projects> projectsCollectionOrphanCheck = customers.getProjectsCollection();
            for (Projects projectsCollectionOrphanCheckProjects : projectsCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Customers (" + customers + ") cannot be destroyed since the Projects " + projectsCollectionOrphanCheckProjects + " in its projectsCollection field has a non-nullable customer field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            em.remove(customers);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Customers> findCustomersEntities() {
        return findCustomersEntities(true, -1, -1);
    }

    public List<Customers> findCustomersEntities(int maxResults, int firstResult) {
        return findCustomersEntities(false, maxResults, firstResult);
    }

    private List<Customers> findCustomersEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Customers.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Customers findCustomers(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Customers.class, id);
        } finally {
            em.close();
        }
    }

    public int getCustomersCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Customers> rt = cq.from(Customers.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
